<template>
  <div>
    <div class="operation-buttons">
      <el-button type="primary" @click="openOrder">开单</el-button>
      <el-button @click="showCombineConfirm">合单</el-button>
      <el-button @click="showSplitConfirm">拆单</el-button>
      <el-button @click="batchOperation">批量操作</el-button>
      <el-button @click="exportData">导出</el-button>
      <div>
        <el-upload
            class="upload-demo"
            ref="uploadRef"
            action="#"
            :auto-upload="false"
            :show-file-list="false"
            :before-upload="beforeUpload"
            :on-change="handleFileChange"
        >
          <el-button size="small" type="primary">选择文件</el-button>
        </el-upload>
        <el-button  @click="submitUpload">上传文件</el-button>
      </div>
<!--      <el-button @click="printData">打印</el-button>-->
    </div>
    <div class="search-area">
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="订单状态">
          <el-select v-model="form.orderStatus">
            <el-option label="请选择" value=""></el-option>
            <el-option label="待审核" value="1"></el-option>
            <el-option label="待调度" value="2"></el-option>
            <el-option label="运输中" value="3"></el-option>
            <el-option label="已签收" value="4"></el-option>
            <el-option label="已拒绝" value="5"></el-option>
            <el-option label="已取消" value="6"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="始发地">
          <el-select v-model="form.origin">
            <el-option label="请选择" value=""></el-option>
            <el-option label="北京" value="北京"></el-option>
            <el-option label="南京" value="南京"></el-option>
            <el-option label="重庆" value="重庆"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目的地">
          <el-select v-model="form.destination">
            <el-option label="请选择" value=""></el-option>
            <el-option label="北京" value="北京"></el-option>
            <el-option label="南京" value="南京"></el-option>
            <el-option label="重庆" value="重庆"></el-option>
            <el-option label="洛阳" value="洛阳"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="下单日期">
          <el-date-picker type="datetime" value-format="yyyy-MM-dd HH:mm:ss" v-model="form.startDate" placeholder="请选择日期"></el-date-picker>
          <span>~</span>
          <el-date-picker type="datetime" value-format="yyyy-MM-dd HH:mm:ss" v-model="form.endDate" placeholder="请选择日期"></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-input v-model="form.keyword" placeholder="请输入关键词搜索"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="query()">搜索</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-table
        ref="multipleTable"
        :data="tableData"
        border
        @selection-change="handleSelectionChange"
        style="width: 100%">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="id" label="序号"></el-table-column>
      <el-table-column prop="orderId" label="订单号"></el-table-column>
      <el-table-column prop="customerName" label="客户名称"></el-table-column>
      <el-table-column prop="customerCode" label="客户编码"></el-table-column>
      <el-table-column prop="origin" label="始发地"></el-table-column>
      <el-table-column prop="destination" label="目的地"></el-table-column>
      <el-table-column prop="orderStatus" label="订单状态">
        <template slot-scope="scope">
          {{scope.row.orderStatus==1 ?'待审核' : scope.row.orderStatus==2?'待调度'
            : scope.row.orderStatus==3?'运输中'
            : scope.row.orderStatus==4?'已签收'
            : scope.row.orderStatus==5?'已拒绝' : '已取消'}}
        </template>
      </el-table-column>
      <el-table-column prop="consignee" label="收货人"></el-table-column>
      <el-table-column prop="shipper" label="发货人"></el-table-column>
<!--      <el-table-column prop="expectedDepartureTime" label="预计发货时间"></el-table-column>-->
<!--      <el-table-column prop="expectedReceiptTime" label="预计收货时间"></el-table-column>-->
      <el-table-column prop="contract" label="合同"></el-table-column>
      <el-table-column prop="transportationType" label="运输类型"></el-table-column>
      <el-table-column prop="goodsType" label="货物类型"></el-table-column>
      <el-table-column prop="quantity" label="货物数量"></el-table-column>
      <el-table-column prop="volume" label="总体积"></el-table-column>
      <el-table-column prop="weight" label="总重量"></el-table-column>
      <el-table-column prop="totalFee" label="运费合计"></el-table-column>
      <el-table-column prop="orderSource" label="订单来源"></el-table-column>
      <el-table-column prop="remarks" label="订单备注"></el-table-column>
      <el-table-column prop="orderTime" label="下单时间"></el-table-column>
      <el-table-column prop="name" label="创建人"></el-table-column>
      <el-table-column prop="createTime" label="创建时间"></el-table-column>
      <el-table-column
          fixed="right"
          label="操作"
          width="100">
        <template slot-scope="scope">
          <el-button  @click="handleClickUpdate(scope.row)" type="text" size="small">调度</el-button>
          <el-button  @click="handleClickUpdate(scope.row)" type="text" size="small">取消合单</el-button>
          <el-button @click="handleClick(scope.row)" type="text" size="small">查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="block">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageNum"
                     :page-sizes="[2, 4, 6, 8]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
                     :total="total">
      </el-pagination>
    </div>

    <!-- 合单确认弹框 -->
    <el-dialog title="合单确认" :visible.sync="combineConfirmVisible" width="30%">
      <p>确定合并选中的订单吗？</p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="combineConfirmVisible = false">取消</el-button>
        <el-button type="primary" @click="doCombineOrder">确定</el-button>
      </span>
    </el-dialog>
    <!-- 拆单确认弹框 -->
    <el-dialog title="拆单确认" :visible.sync="splitConfirmVisible" width="30%">
      <p>确定拆分选中的订单吗？</p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="splitConfirmVisible = false">取消</el-button>
        <el-button type="primary" @click="doSplitOrder">确定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import axios from 'axios';
import router from "@/router";

export default {
  data() {
    return {
      form: {
        orderStatus: '',
        origin: '',
        destination: '',
        startDate: '',
        endDate: '',
        keyword: ''
      },
      multipleSelection: [],
      tableData: [],
      total: 0,
      pageNum: 1,
      pageSize: 2,
      pojo: {},
      dialogFormVisible: false,
      dialogVisible: false,
      bjyx: {},
      rejecting: false,
      mode: {
        title: "",
        url: ``,
      },
      imageUrl: '',
      allList: [],
      ids: [],
      selectedFile: null,
      combineConfirmVisible: false, // 合单确认弹框显示状态
      splitConfirmVisible: false // 拆单确认弹框显示状态
    };
  },
  methods: {
    resetForm() {
      this.form = {
        orderStatus: '',
        origin: '',
        destination: '',
        startDate: '',
        endDate: '',
        keyword: ''
      };
    },
    handleClick(row){
      this.$router.push({name:'orderDetail',params:{id:row.id}})
    },
    openOrder() {
      router.push('/order/bill');
    },
    showCombineConfirm() {
      if (this.multipleSelection.length < 2) {
        this.$message.warning('请至少选择两个订单进行合单操作');
        return;
      }
      this.combineConfirmVisible = true;
    },
    doCombineOrder() {
      // 这里应调用合单的接口，目前只是简单打印选中的订单信息
      console.log('执行合单操作，选中的订单：', this.multipleSelection);
      this.combineConfirmVisible = false;
    },
    showSplitConfirm() {
      if (this.multipleSelection.length!== 1) {
        this.$message.warning('请仅选择一个订单进行拆单操作');
        return;
      }
      this.splitConfirmVisible = true;
    },
    doSplitOrder() {
      // 这里应调用拆单的接口，目前只是简单打印选中的订单信息
      console.log('执行拆单操作，选中的订单：', this.multipleSelection[0]);
      this.splitConfirmVisible = false;
    },
    batchOperation() {
      console.log('批量操作');
    },
    beforeUpload(file) {
      // 可以在这里进行文件类型和大小的验证
      const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || file.type === 'application/vnd.ms-excel';
      if (!isExcel) {
        this.$message.error('请上传 Excel 文件');
        return false;
      }
      return true;
    },
    handleFileChange(file) {
      this.selectedFile = file;
    },
    submitUpload() {
      if (!this.selectedFile) {
        this.$message.error('请选择要上传的文件');
        return;
      }
      const formData = new FormData();
      formData.append('file', this.selectedFile.raw);

      axios.post('http://localhost:10086/orders/order/importExcel', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
          .then(response => {
            this.$message.success('文件上传成功');
            this.$refs.uploadRef.clearFiles();
            this.selectedFile = null;
          })
          .catch(error => {
            this.$message.error('文件上传失败：' + error.message);
          });
    },
    //导出
    exportData() {
      const exportUrl = 'http://localhost:10086/orders/order/exportExcel';
      window.location.href = exportUrl;
    },

    // printData() {
    //   console.log('打印操作');
    // },


    updateCourseStatus(newStatus, id) {
      axios.get(`http://localhost:1129/course/updateStatus/${newStatus}/${id}`).then(res => {
        if (res.data.code === 1) {
          this.$message({
            message: '修改成功',
            type: 'success'
          });
          this.query();
        } else {
          this.handleRequestError('修改失败');
        }
      }).catch(error => {
        this.handleRequestError('修改失败');
      });
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.query();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.pageNum = val;
      this.query();
    },
    query() {
      axios.post("http://localhost:10086/orders/order/getOrders?pageNum=" +  this.pageNum + "&pageSize=" +this.pageSize,this.form)
          .then(res => {
        console.log(res.data);
        this.tableData = res.data.data.list;
        this.total = res.data.data.total;
        if (res.data.code === 1) {
          this.$message({
            message: '查询成功🌺',
            type: 'success'
          });
        } else {
          this.handleRequestError('查询失败');
        }
      }).catch(error => {
        this.handleRequestError('查询失败');
      });
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
    },
    handleClickUpdate(row) {
      this.mode.title = "修改";
      this.mode.url = 'http://localhost:1129/course/update';
      this.pojo = row;
      this.imageUrl = this.pojo.image;
      this.dialogFormVisible = true;
    },

    handledelClick(row) {
      console.log(row);
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.get(`http://localhost:1129/course/delete/${row.id}`).then(res => {
          if (res.data.code === 1) {
            this.$message({
              message: '删除成功',
              type: 'success'
            });
            this.query();
          } else {
            this.handleRequestError('删除失败');
          }
        }).catch(error => {
          this.handleRequestError('删除失败');
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    toDelete() {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.ids = [];
        for (let i = 0; i < this.allList.length; i++) {
          this.ids.push(this.allList[i].id);
        }
        axios.post("http://localhost:1129/course/deleteAll", this.ids).then(res => {
          if (res.data === 0) {
            this.$message.success("恭喜你，删除成功！");
            this.query();
          } else {
            this.handleRequestError('删除失败');
          }
        }).catch(error => {
          this.handleRequestError('删除失败');
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleSelectionChange(val) {
      this.allList = val;
      this.multipleSelection = val; // 增加这一行，同步更新 multipleSelection
    },
    handleRequestError(message) {
      this.$message.error(message);
    }
  },
  created() {
    this.query();
  }
};
</script>

<style>
.upload-demo {
  display: inline-block;
  margin-right: 10px;
}

.search-area {
  margin-bottom: 20px;
}
.operation-buttons {
  margin-bottom: 20px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.item {
  margin-top: 10px;
  margin-right: 40px;
}
.el-dropdown {
  vertical-align: top;
}
.el-dropdown+.el-dropdown {
  margin-left: 15px;
}
.el-icon-arrow-down {
  font-size: 12px;
}
</style>
